package com.juyu.miliao.common.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.builder.BillDetailBeansMqMessageBuilder;
import com.juyu.miliao.common.constant.BeansType;
import com.juyu.miliao.common.constant.BillDetailBeansMqKey;
import com.juyu.miliao.common.constant.UserLoginRedisKey;
import com.juyu.miliao.common.constant.UserWalletBeansSumMqKey;
import com.juyu.miliao.common.constant.enumRedisKey.EnumRedisKey;
import com.juyu.miliao.common.domain.NetEaseConfig;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.domain.dto.BillDetailBeansDTO;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.MessageSystemUtil;
import com.juyu.miliao.common.util.ServletTool;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Data
@Component
public class JsonAuthSuccessHandler implements AuthenticationSuccessHandler {

    private final String EVERYDAY_MESSAGE = "平台近期接到多位用户举报，某些非认证主播利用平台私聊功能，"
            + "引导用户添加私人微信、QQ等第三方社交帐号，并索要红包、拉黑用户、骗取他人钱财。"
            + "请用户注意提防，于平台内沟通交流，避免被骗与财产损失。"
            + "若发现上述情况，请及时联系官方客服举报，感谢您的支持。";

    private final Logger logger = LoggerFactory.getLogger(JsonAuthSuccessHandler.class);

    private AmqpTemplate amqpTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;


    private static final Map<String, String> appPackageIdMap = new HashMap<>();

    public JsonAuthSuccessHandler() {
        appPackageIdMap.put("huami", "寻寻");
        appPackageIdMap.put("miban", "密伴");
        appPackageIdMap.put("tcyl", "同城夜聊");
        appPackageIdMap.put("mmjy", "陌陌约会");
        appPackageIdMap.put("yueai", "约爱");
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        request.getSession();
        String sessionId = request.changeSessionId();
        Subject userDetails = (Subject) authentication.getPrincipal();
        if (request.getServletPath().equals("/register/phoneNumber")
                || request.getServletPath().equals("/login/thirdParty")
                || request.getServletPath().equals("/login/automatic")
                || request.getServletPath().equals("/login/verificationCode")) {// 判断是否是创建请求
            String createLogInfo = NetEaseCloudUserService.createNetEaseId(userDetails.getId() + "", sessionId);// 创建网易云通信ID
            // 如果创建id失败，则更新id
            if (!createLogInfo.substring(createLogInfo.indexOf("code") + 6, createLogInfo.indexOf("code") + 9)
                    .equals("200")) {
                String updateLogInfo = NetEaseCloudUserService.updateNetEaseId(userDetails.getId() + "", sessionId);

                if (logger.isInfoEnabled()) {
                    logger.info("创建失败！网易云通信ID更新：" + updateLogInfo);// 更新网易云通信ID
                }
            } else {
                if (logger.isInfoEnabled()) {
                    logger.info("创建网易云通信ID成功：" + createLogInfo);
                    // 发送系统消息
                    newUser(userDetails.getId(), userDetails.getAppPackageId());

                    String updateLogInfo = NetEaseCloudUserService.updateUserInfo(userDetails.getId(),
                            userDetails.getNickName(), userDetails.getIcon());
                    if (!updateLogInfo.substring(updateLogInfo.indexOf("code") + 6, updateLogInfo.indexOf("code") + 9)
                            .equals("200")) {
                        if (logger.isInfoEnabled()) {
                            logger.info("更新用户基本信息失败！网易云通信ID更新：" + updateLogInfo);// 更新网易云通信ID
                        }
                    }
                }
            }
        } else {
            String updateLogInfo = NetEaseCloudUserService.updateNetEaseId(userDetails.getId() + "", sessionId);// 更新网易云通信ID
            if (logger.isInfoEnabled()) {
                logger.info("网易云通信ID更新：" + updateLogInfo);
            }
        }

        addUserByAppPackageId(userDetails);
        //设置token k-v缓存
        request.getSession().setAttribute(
                FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, userDetails.getId() + "");
        Map<String, String> map = new HashMap<>();
        map.put("token", sessionId);
        map.put("userId", userDetails.getId() + "");
        Boolean firstReg = userDetails.getFirstRegister();
        map.put("firstRegister", firstReg == null ? "false" : String.valueOf(firstReg));
        Boolean isAudit = userDetails.getIsAudit();
        map.put("jzSC", isAudit == null ? "false" : String.valueOf(isAudit));
        map.put("isVip", userDetails.getIsVip() + "");
        map.put("isHost", userDetails.getIsHost() + "");
        map.put("sex", userDetails.getSex() + "");
        map.put("isNewUserBindingPhone",userDetails.getIsNewUserBindingPhone()+"");
        //map.put("phone",userDetails.getUsername());
        //每天第一次登陆发送系统消息
//        sendEveryDayLoginMessage(userDetails.getId());
        //将第一次注册用户放入rabbitmq中
        if (firstReg != null && firstReg) {
            amqpTemplate.convertAndSend("REGISTER_FANOUT_EXCHANGE", "", userDetails.getId() + "");
            //1.5.1新注册用户，不用发送这条系统消息
//			if (userDetails.getSex() == 2) {
//				String message = "恭喜您成功注册，踏上寻友之旅！我们诚邀您申请认证，认证后您能通过聊天互动、分享照片视频等多种玩法获得钻石奖励。所有钻石均可提现,体验交友赚钱的快感！";
//				MessageSystemUtil.userCertificationHost(userDetails.getId(),message);
//			}else if(userDetails.getSex() == 1){
//				String message = "恭喜您成功注册，踏上寻友之旅！温馨提醒您，请在“发现”界面找寻您心仪的那个 TA，带上你的礼物与 TA 来一次亲密接触！认准 TA 的星级标识，星级越高体验越好!";
//				MessageSystemUtil.userCertificationHost(userDetails.getId(),message);
//			}
            //用户注册第一次注册发送系统消息，温馨提示
            MessageSystemUtil.sendRegisterMessage(userDetails.getId());
            //新注册用户赠送1000寻豆,不用了
//            String CTT = ZoneId.SHORT_IDS.get("CTT");
//            BillDetailBeansMqMessageBuilder builder = new BillDetailBeansMqMessageBuilder();
//            BillDetailBeansDTO billDetailBeansDTO = builder.userId(userDetails.getId()).beans(10000)
//                    .beansType(BeansType.NEW_USER_GIVE_BEANS).
//                            createDate(LocalDate.now(ZoneId.of(CTT)))
//                    .createTime(LocalDateTime.now(ZoneId.of(CTT))).build();
//            /**
//             * 新注册用户送寻豆,并入账单
//             */
//            amqpTemplate.convertAndSend(UserWalletBeansSumMqKey.USER_BEANS_EXCHANGE_KEY,
//                    UserWalletBeansSumMqKey.USER_WALLET_BEANS_ROUNTING_KEY,
//                    objectMapper.writeValueAsString(billDetailBeansDTO));


        }
        ServletTool.writeJSONStr(response, new ObjectMapper().writeValueAsString(map));
    }

    /**
     * 记录用户最近一次登录、注册是否使用的mmjy包---用于发送私照和礼物弹窗
     */
    private void addUserByAppPackageId(Subject userDetails) {
        if (userDetails.getAppPackageId().equals("mmjy")) {
            stringRedisTemplate.opsForSet().add(EnumRedisKey.SET_USER_APPPACKAGEID.getValue("mmjy"), userDetails.getId() + "");
        } else {
            stringRedisTemplate.opsForSet().remove(EnumRedisKey.SET_USER_APPPACKAGEID.getValue("mmjy"), userDetails.getId() + "");
        }
        if (userDetails.getAppPackageId().equals("huami")) {
            stringRedisTemplate.opsForSet().add(EnumRedisKey.SET_USER_APPPACKAGEID.getValue("huami"), userDetails.getId() + "");
        } else {
            stringRedisTemplate.opsForSet().remove(EnumRedisKey.SET_USER_APPPACKAGEID.getValue("huami"), userDetails.getId() + "");
        }
    }

    protected final void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }

    public void newUser(Long userId, String appPackageId) {
        try {
            String appName = appPackageIdMap.get(appPackageId);
            if (appName == null || appName.equals("")) {
                appName = "本平台";
            }
            logger.info("systemMessage-------newUser:::::::进入发送系统消息，appkey：{}===Secret:{}", NetEaseConfig.getAppKey(), NetEaseConfig.getAppSecret());
            String message = "欢迎你来到" + appName + "!"
                    + "在这儿，美女帅哥陪聊是可以赚钻石挣财富，她们会主动找你哦，让我们一起开始新的小世界吧。";
            Map<String, String> map = new HashMap<String, String>();
            map.put("title", appName);
            map.put("type", "1");
            map.put("message", message);
            ObjectMapper mapper = new ObjectMapper();
            String createLogInfo = NetEaseCloudUserService.getSystemMessage(mapper.writeValueAsString(map), userId);
            if (!createLogInfo.substring(createLogInfo.indexOf("code") + 6, createLogInfo.indexOf("code") + 9)
                    .equals("200")) {
                if (logger.isErrorEnabled()) {
                    logger.error("newUser系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                }
            }
            logger.info("systemMessage-------newUser:::::::createLogInfo={}", createLogInfo);
        } catch (Exception e) {
            logger.error("newUser系统消息发送IM错误：参数:userId={}" + userId);
        }
    }

    /**
     * 用户每天第一次登陆发送系统消息
     */
    private void sendEveryDayLoginMessage(long userId) {
        if (!stringRedisTemplate.opsForSet().isMember(EnumRedisKey.SET_USER_LOGIN_EVERYDAY.getValue(), userId + "")) {
            stringRedisTemplate.opsForSet().add(EnumRedisKey.SET_USER_LOGIN_EVERYDAY.getValue(), userId + "");
            MessageSystemUtil.sendCustomSystemMessage(userId, EVERYDAY_MESSAGE);
        }
    }

}
